package cn.tedu.springboot.security.service.impl;

import cn.tedu.springboot.security.mapper.AdminMapper;
import cn.tedu.springboot.security.pojo.dto.AdminLoginDTO;
import cn.tedu.springboot.security.pojo.vo.AdminListItemVO;
import cn.tedu.springboot.security.pojo.vo.AdminLoginInfoVO;
import cn.tedu.springboot.security.service.IAdminService;
import cn.tedu.springboot.security.sety.AdminDetails;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @author BJ
 * @date 2022/10/22 15:15
 * 管理员的业务实现类
 */
@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    AuthenticationManager authenticationManager;
    @Value("${csmall.jwt.secret-key}")
    private String secretKey;

    @Override
    public String login(AdminLoginDTO adminLoginDTO) {
        log.debug("开始处理 [管理员登录] 的业务!参数:{}",adminLoginDTO);
        Authentication authenticationToken = new UsernamePasswordAuthenticationToken(
                adminLoginDTO.getUsername(), adminLoginDTO.getPassword()
        );
        Authentication authenticateResult = authenticationManager.authenticate(authenticationToken);
        log.debug("执行认证成功!authenticationManager返回: {}",authenticateResult);

        //====以上认证的过程中,security 认证通过则向下执行,不通过则抛出异常====
        // principal 当事人,封装的用户登录的信息(将被用作封装jwt)
        Object principal = authenticateResult.getPrincipal();
        AdminDetails adminDetails = (AdminDetails) principal;

        log.debug("开始尝试生成 jwt...");
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id",adminDetails.getId());
        claims.put("username",adminDetails.getUsername());
        claims.put("authorities", JSON.toJSONString(adminDetails.getAuthorities()));

        Date expirationDate = new Date(System.currentTimeMillis() + 10 * 24 * 60 * 60 * 1000);
        String jwt = Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        log.debug("返回JWT数据：{}", jwt);
        return jwt;
        //===至此，当客户端向服务器端提交登录请求，且登录成功后，将得到服务器端响应的JWT数据，
        // 此JWT中包含了id和username。authorities===
    }

    @Override
    public List<AdminListItemVO> list() {
        log.debug("开始处理 [管理员列表] 业务!");
        List<AdminListItemVO> admins = adminMapper.list();
        Iterator<AdminListItemVO> adminListItems = admins.iterator();
        while (adminListItems.hasNext()) {
            AdminListItemVO admin = adminListItems.next();
            if (admin.getId() == 1) {
                adminListItems.remove();
                break;
            }
        }
        return admins;
    }
}
